package com.sh.mytool.cv.controller;

import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.sh.common.extjs.CUDResult;
import com.sh.common.extjs.GetResult;
import com.sh.common.web.ResponseHandle;
import com.sh.mytool.cv.domain.Article;
import com.sh.mytool.cv.service.ArticleService;

@Controller
public class ArticleController {

    @Resource(name="articleService")
    private ArticleService articleService;

    @InitBinder
    public void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(df, true));
    }

    @RequestMapping(value = "/article/get", method = RequestMethod.POST)
    public void columnGet(@RequestParam(value="id") Long id, HttpServletResponse response, PrintWriter out) throws Exception{
        Article result = articleService.get(id);
        Boolean isSuccess = false;
        if(result != null){
            isSuccess = true;
        }
        String json = ResponseHandle.handleJson("", "", new GetResult(isSuccess, result), false);
        response.setCharacterEncoding("UTF-8");
        out.write(json);
        out.flush();
        out.close();
    }

    @RequestMapping(value = "/article/edit", method = RequestMethod.POST)
    public void columnEdit(Article bean, HttpServletResponse response, PrintWriter out) throws Exception{
        boolean isSuccess = true;
        try {
            articleService.update(bean);
        } catch (Exception e) {
            e.printStackTrace();
            isSuccess = false;
        }
        String json = ResponseHandle.handleJson("", "", new CUDResult(isSuccess), false);
        response.setCharacterEncoding("UTF-8");
        out.write(json);
        out.flush();
        out.close();
    }

    public ArticleService getArticleService() {
        return articleService;
    }

    public void setArticleService(ArticleService articleService) {
        this.articleService = articleService;
    }

}
